<?php

/**
 * 写日志
 *
 * @author 煤老板 <meok23@sina.com>
 * @data   2017-06-05
 */

namespace app\common\logic;

use fw\base\Conf;
use fw\base\Instance;
use fw\db\DB;
use fw\tool\Json;
use fw\tool\Request;

class Log
{
    use Instance;

    /**
     * 写错误日志。
     *
     * @param array $args 数组参数
     *
     * ```
     *  string       filename       所在文件
     *  string       breakpoint     触发日志的地方，断点：函数名、行数……
     *  array|mixed  response       响应值：code+msg+data
     *  array|mixed  param          函数参数
     * ```
     */
    public function add($args)
    {
        $response = Request::input($args, 'response');
        $param = Request::input($args, 'param');
        $create_time = time();

        $data = [
            'filename'      => Request::input($args, 'filename'),
            'breakpoint'    => Request::input($args, 'breakpoint'),
            'response_code' => Request::input($response, 'code'),
            'check_status'  => 0,
        ];

        if (Conf::$all['log_type'] == 0) {
            // 日志写到数据库
            $data['response'] = Json::encode($response);
            $data['param'] = Json::encode($param);
            $data['create_time'] = $create_time;

            DB::table('log_error')->insert($data);
        } else {
            // 日志写到文件
            $data['response'] = $response;
            $data['param'] = $param;
            $data['create_time'] = date('Y-m-d H:i:s', $create_time);

            $text = Json::encode($data) . PHP_EOL;
            file_put_contents(Conf::$all['log_path'], $text, FILE_APPEND);
        }
    }
}
